package com.hepinghospital.user.ui.activity.userinfo;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.base.BaseApplication;
import com.hepinghospital.user.eventbus.Logout;
import com.hepinghospital.user.service.WebSocketService;
import com.hepinghospital.user.ui.WebViewActivity;
import com.hepinghospital.user.ui.dialog.ApplyPermissionDialog;
import com.hepinghospital.user.ui.dialog.ApplyQuitDialog;
import com.hepinghospital.user.ui.dialog.SelectPicModeDialog;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.PermissionsChecker;
import com.hepinghospital.user.util.ToastUtil;
import com.hepinghospital.user.util.UploadImageUtil;
import com.rest.business.RestProxy;
import com.rest.client.RestClient;
import com.rest.observer.BaseObserver;
import com.rest.response.PicUploadResponse;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.PackageUtils;
import jz.joyoung.robot.util.PreferencesHelper;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.UriUtils;
import jz.joyoung.robot.util.UtilString;


/**
 * @Description: 个人信息
 * @Author: lzp
 * @CreateDate: 2022/3/23 14:49
 * @UpdateRemark: 更新说明
 */
public class UserInfoActivity extends BaseActivity {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.avatar)
    ImageView avatar;
    @BindView(R.id.rl_avatar)
    RelativeLayout rlAvatar;
    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.rl_name)
    RelativeLayout rlName;
    @BindView(R.id.btn_update_password)
    RelativeLayout btnUpdatePassword;
    @BindView(R.id.btn_address)
    RelativeLayout btnAddress;
    @BindView(R.id.btn_logout)
    TextView btnLogout;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.tv_manufacturer)
    TextView tvManufacturer;

    private SelectPicModeDialog mSelectPicModeDialog = null;
    //原图像 URI
    public Uri imgUriOri;
    //原图像 路径
    public static String imgPathOri, resourceId;
    public ProgressDialog dialog;
    public static final int REQUEST_EDIT_NAME = 0x033;
    public static final int REQUEST_EDIT_MOBILE = 0x034;
    public static final int REQUEST_OPEN_CAMERA = 0x011;
    public static final int REQUEST_GALLERY = 0x022;
    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
    };
    private PermissionsChecker mPermissionsChecker; // 权限检测器

    @SuppressLint("SetTextI18n")
    @Override
    protected void initViews() {

        tvTitle.setText("个人信息");
        tvVersion.setText(PackageUtils.getVersionName(mContext));
        tvManufacturer.setText(Build.MANUFACTURER + " " + Build.MODEL);
        if (!UtilString.isEmpty(BaseApplication.avatar)) {
            ImageLoaderHelper.getInstance().setCirclePicture(mContext, avatar, BaseApplication.avatar);
        } else {
            if ("女".equals(BaseApplication.sex)) {
                avatar.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_head_user_woman));
            } else {
                avatar.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_head_user_man));
            }
        }

        if (!UtilString.isEmpty(BaseApplication.name)) {
            tvUsername.setText(BaseApplication.name);
        }
        mPermissionsChecker = new PermissionsChecker(mContext);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_userinfo;
    }


    @OnClick({R.id.btn_add_family, R.id.rl_avatar, R.id.rl_name, R.id.btn_update_password, R.id.btn_address, R.id.btn_logout, R.id.rl_rules, R.id.rl_delete_phone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_avatar:
                // 缺少权限时, 进入权限配置页面
                if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                    getPermission();
                } else {
                    showSelectHeadPicDialog();
                }
                break;
            case R.id.rl_name:
                //改昵称
                Intent intent = new Intent(mContext, UserInfoEditActivity.class);
                intent.putExtra("editType", "name");
                intent.putExtra("editData", BaseApplication.name);
                startActivityForResult(intent, REQUEST_EDIT_NAME);
                break;
            case R.id.rl_phone:
                //改昵称
                Intent intent1 = new Intent(mContext, UserInfoEditActivity.class);
                intent1.putExtra("editType", "telphone");
                intent1.putExtra("editData", BaseApplication.mobile);
                startActivityForResult(intent1, REQUEST_EDIT_MOBILE);
                break;
            case R.id.btn_update_password:
                startActivity(UpdatePasswordActivity.class);
                break;
            case R.id.btn_address:
                Intent intentAddress = new Intent(this, MyAddressActivity.class);
                intentAddress.putExtra("isFromMine", true);
                startActivity(intentAddress);
                break;
            case R.id.btn_logout:
                logOut();
                break;
            case R.id.rl_rules:
                startActivity(new Intent(mContext, WebViewActivity.class).putExtra("fromWhere", "LoginActivity").putExtra("rulesType", "7"));
                break;
            case R.id.rl_delete_phone:
                showApplyQuitDialog();
                break;
            default:
                break;
        }
    }

    private void logOut() {

        RestProxy.getInstance().logOut(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String s) {
                stopService(new Intent(mContext, WebSocketService.class));
                BaseApplication.avatar = "";
                RestClient.getInstance().token = "";
                PreferencesHelper.getInstance().set(mContext, "accessToken", "");
                EventBus.getDefault().postSticky(new Logout(1));
                EventBus.getDefault().postSticky(new Logout(3));
                RestClient.getInstance().clearSession();
                startActivity(LoginActivity.class);
                finish();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {
            }
        });
    }

    private void showSelectHeadPicDialog() {
        if (mSelectPicModeDialog == null) {
            // 初始化点击头像弹出的对话框
            mSelectPicModeDialog = SelectPicModeDialog.newInstance();
            mSelectPicModeDialog.setOnItemClickListener(new SelectPicModeDialog.OnItemClickListener() {
                @Override
                public void takePhotoClick() {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File oriPhotoFile = null;
                    try {
                        oriPhotoFile = createOriImageFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                        imgUriOri = Uri.fromFile(oriPhotoFile);
                    } else {
                        assert oriPhotoFile != null;
                        imgUriOri = FileProvider.getUriForFile(UserInfoActivity.this, UIConstants.FILE_PROVIDER_URI, oriPhotoFile);
                    }
//                    phoneCamearUri = FileProvider.getUriForFile(PersonInfoActivity.this,"com.joyoung.robot.phone.provider",file);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUriOri);
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    startActivityForResult(intent, REQUEST_OPEN_CAMERA);
                }

                @Override
                public void pickFromAlbumClick() {
                    @SuppressLint("IntentReset") Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(intent, REQUEST_GALLERY);
                }
            });
        }
        mSelectPicModeDialog.show(getSupportFragmentManager(), "SelectPicModeDialog");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        //data的返回值根据
        switch (requestCode) {

            case REQUEST_OPEN_CAMERA:
                showLoadingDialog(mContext);
                UploadImageUtil.uploadPic("3", "30", imgPathOri, "0", new UploadImageUtil.UploadCallBack() {
                    @Override
                    public void success(PicUploadResponse data) {
                        uploadImageSuccess(data);
                    }

                    @Override
                    public void fail() {
                        dismissLoadingDialog();
                    }
                });
                break;
            case REQUEST_GALLERY:
                Log.e("相册头像---", data.toString());
                if (data != null) {
                    Uri imgUriSel = data.getData();
                    String imgPathSel = UriUtils.formatUri(this, imgUriSel);
                    showLoadingDialog(mContext);
                    UploadImageUtil.uploadPic("3", "30", imgPathSel, "0", new UploadImageUtil.UploadCallBack() {
                        @Override
                        public void success(PicUploadResponse data) {
                            uploadImageSuccess(data);
                        }

                        @Override
                        public void fail() {
                            dismissLoadingDialog();
                        }
                    });
                }

                break;
            case REQUEST_EDIT_NAME:
                tvUsername.setText(data.getStringExtra("editData"));
                break;

            case REQUEST_EDIT_MOBILE:
                tvPhone.setText(data.getStringExtra("editData"));
                break;

            default:
                break;
        }
    }

    private void uploadImageSuccess(PicUploadResponse data) {
        try {
            runOnUiThread(() -> {
                dismissLoadingDialog();
                Log.e("头像---", data.shareUrl);
                if (!UtilString.isEmpty(data.shareUrl)) {
                    BaseApplication.avatar = data.shareUrl;
                    ImageLoaderHelper.getInstance().GlideCircleImageLoader(mContext, data.shareUrl, avatar);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建原图像保存的文件
     */
    protected File createOriImageFile() throws IOException {
        @SuppressLint("SimpleDateFormat") String imgNameOri = "HomePic_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File pictureDirOri = new File(Objects.requireNonNull(getExternalFilesDir(Environment.DIRECTORY_PICTURES)).getAbsolutePath() + "/OriPicture");
        if (!pictureDirOri.exists()) {
            pictureDirOri.mkdirs();
        }
        File image = File.createTempFile(
                imgNameOri,         /* prefix */
                ".jpg",             /* suffix */
                pictureDirOri       /* directory */
        );
        imgPathOri = image.getAbsolutePath();
        return image;
    }

    @SuppressLint("CheckResult")
    private void getPermission() {
        ApplyPermissionDialog applyPermissionDialog = ApplyPermissionDialog.newInstance("3", true);
        applyPermissionDialog.show(getSupportFragmentManager(), "applyPermissionDialog");
        applyPermissionDialog.setmListener(new ApplyPermissionDialog.OnItemClickListener() {

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onConfirm() {
                RxPermissions permissions = new RxPermissions(UserInfoActivity.this);
                permissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                        .subscribe(granted -> {
                            if (granted) {
                                //已经打开权限
                                showSelectHeadPicDialog();
                            } else {
                                ToastUtil.showToast(mContext, "请同意相册和存储权限，否则功能无法使用");
                                startNotificationSetting(mContext);
                            }
                        });
            }

            @Override
            public void onCancel() {

            }
        });
    }

    private void showApplyQuitDialog() {
        ApplyQuitDialog applyQuitDialog = ApplyQuitDialog.newInstance("1", true);//申请退药
        applyQuitDialog.show(getSupportFragmentManager(), "applyQuitDialog");
        applyQuitDialog.setmListener(new ApplyQuitDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                RestProxy.getInstance().modifyUserStatus("", new BaseObserver<String>() {
                    @Override
                    public void onError(Throwable e) {
                        ToastUtil.onError(mContext, e);
                    }

                    @Override
                    public void onSuccess(String result) {
                        try {
                            PreferencesHelper.getInstance().set(mContext, "accessToken", "");
                            RestClient.getInstance().token = "";
                            stopService(new Intent(mContext, WebSocketService.class));
                            RestClient.getInstance().clearSession();
                            startActivity(new Intent(mContext, LoginActivity.class));
                            finish();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

            @Override
            public void onCancel() {

            }
        });
    }
}
